×
☰ See All Chapters

How to create component in React using JSX

Step 1: Create ReactJS Project

Create ReactJS project using create-react-app utility (Refer previous chapters) and import it to eclipse. Initial project directory would like below image:

how-to-create-component-in-react-using-jsx-0
 

Step 2: Create Component

Create a component file inside src folder. You can create a separate directory for better structure and create your component inside the directory.

firstcomponent.js

function FirstComponent() {

  return (

    <h1> My First Component</h1>

  );

}

 

export default FirstComponent;

 

Step 3: Delete the default components

When you create ReactJS project by using create-react-app utility, it creates few default components like App and Header. Delete these default components and all related test files and logo file. Delete App.js, App.test.js, Header.js, logo.svg, setupTests.js files. Final directory structure looks like below image:

how-to-create-component-in-react-using-jsx-1
 

Step 4: Use the component and check the output

Using the FirstComponent from index.js file.

index.js

import React from 'react';

import ReactDOM from 'react-dom';

import './index.css';

import FirstComponent from './components/firstcomponent';

import reportWebVitals from './reportWebVitals';

 

ReactDOM.render(

  <React.StrictMode>

    <FirstComponent></FirstComponent>

  </React.StrictMode>,

  document.getElementById('root')

);

 

reportWebVitals();

Now you should see the output where the FirstComponent is rendered on interface as shown below:

how-to-create-component-in-react-using-jsx-2
 

All Chapters
Author